<?php

/**
 * 合同文档信息仓库
 * @author wangwx 2015-5-16
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\support\Helper;
use common\entities\myhtsq\ContractDocumentEntity;
use common\models\myhtsq\ContractDocumentModel;
class ContractDocumentRepository extends BaseRepository {

    /**
     * 构造函数
     * @param type $config
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }
    
    /**
     * 根据合同id,获取合同文档信息列表
     * @param string $contractId 合同id
     * @return array
     */
    public static function getContractDocumentListByContractId($contractId) {
    	return ContractDocumentEntity::find()->select('myscrm_contract_document.*,myscrm_erp_user.UserName as keeper_name')->where(['contract_id'=>$contractId])
    	->leftJoin('myscrm_erp_user','myscrm_erp_user.UserGUID = myscrm_contract_document.keeper')->asArray()->all();
    }
    
    /**
     * 根据合同id,文档id 删除文档信息
     * @param string $contrackId 合同id
     * @param string $documentId 文档id
     * @return boolean
     */
    public static function deleteContractDocumentByContractIdAndDocumentId($contractId,$documentId) {
    	return ContractDocumentEntity::deleteAll(['document_id'=>$documentId,'contract_id'=>$contractId]);
    }
    
    /**
     * 新增合同文档信息
     * @param common\models\myhtsq\ContractDocumentModel $contractDocumentModel
     * @return boolean|string
     */
    public static function addContractDocument( ContractDocumentModel $contractDocumentModel) {
    	$contractDocumentEntity = new ContractDocumentEntity();
    	$contractDocumentEntity->setAttributes($contractDocumentModel->attributes);
    	$contractDocumentEntity->document_id = \common\support\StringHelper::uuid();
    	if ($contractDocumentEntity->save()) {
    		return $contractDocumentEntity->document_id;//新增成功，返回主键id
    	}else{
    		var_dump($contractDocumentEntity->getAllFirstErrorMessage());
    		return false;
    	}
    }
    
    /**
     * 更新合同文档信息
     * @param common\models\myhtsq\ContractDocumentModel $contractDocumentModel
     * @return boolean|string
     */
    public static function updateContractDocument( ContractDocumentModel $contractDocumentModel) {
    	$contractDocumentEntity = new ContractDocumentEntity();
    	$contractDocumentEntity->setAttributes($contractDocumentModel->attributes);
    	
    	$contractDocumentModelInfo = ContractDocumentEntity::find()->where(['document_id'=>$contractDocumentModel->document_id])->one();
    	$data = $contractDocumentModel->attributes;
    	
    	$contractDocumentModelInfo->load($data,'');
    	if ($contractDocumentModelInfo->save()) {
    		return $contractDocumentModelInfo->document_id;//更新成功，返回主键id
    	}else{
    		return false;
    	}
    }

   
}
